package com.fjh.springboot_01.service.impl;

import com.fjh.springboot_01.pojo.homework.Homework;
import com.fjh.springboot_01.pojo.homework.HomeworkQuestion;
import com.fjh.springboot_01.pojo.homework.HomeworkAnswer;
import com.fjh.springboot_01.pojo.homework.MistakeBook;
import com.fjh.springboot_01.mapper.HomeworkMapper;
import com.fjh.springboot_01.mapper.HomeworkQuestionMapper;
import com.fjh.springboot_01.mapper.HomeworkAnswerMapper;
import com.fjh.springboot_01.service.HomeworkService;
import com.fjh.springboot_01.service.MistakeBookService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class HomeworkServiceImpl implements HomeworkService {
    @Autowired
    private HomeworkMapper homeworkMapper;
    
    @Autowired
    private HomeworkQuestionMapper questionMapper;
    
    @Autowired
    private HomeworkAnswerMapper answerMapper;
    
    @Autowired
    private MistakeBookService mistakeBookService;
    
    @Autowired
    private AIService aiService;

    @Override
    @Transactional
    public void createHomework(Homework homework, List<HomeworkQuestion> questions) {
        // 验证家教预约ID是否存在
        if (homework.getTutoringBookingId() == null) {
            throw new IllegalArgumentException("家教预约ID不能为空");
        }
        
        // 设置初始状态为未完成
        homework.setStatus(0);
        try {
            homeworkMapper.insert(homework);
            
            // 批量插入题目
            for (HomeworkQuestion question : questions) {
                question.setHomeworkId(homework.getId());
                questionMapper.insert(question);
            }
        } catch (Exception e) {
            throw new RuntimeException("创建作业失败：" + e.getMessage());
        }
    }

    @Override
    public Homework getHomeworkById(Integer id) {
        System.out.println("开始获取作业详情，作业ID: " + id);
        Homework homework = homeworkMapper.findById(id);
        System.out.println("获取到的作业基本信息: " + homework);
        
        if (homework != null) {
            // 获取作业题目
            List<HomeworkQuestion> questions = questionMapper.findByHomeworkId(id);
            System.out.println("获取到的作业题目数量: " + questions.size());
            System.out.println("作业题目详情: " + questions);
            
            // 获取该作业的所有学生答案
            List<HomeworkAnswer> answers = answerMapper.findByHomeworkId(id);
            System.out.println("获取到的学生答案数量: " + answers.size());
            System.out.println("学生答案详情: " + answers);
            
            // 将答案关联到对应的题目
            for (HomeworkQuestion question : questions) {
                // 找到该题目的答案
                HomeworkAnswer answer = answers.stream()
                    .filter(a -> a.getQuestionId().equals(question.getId()))
                    .findFirst()
                    .orElse(null);
                    
                question.setStudentAnswer(answer);
                System.out.println("题目 " + question.getId() + " 关联的答案: " + answer);
            }
            
            homework.setQuestions(questions);
        }
        return homework;
    }

    @Override
    public List<Homework> getTeacherHomeworks(Integer teacherId) {
        return homeworkMapper.findByTeacherId(teacherId);
    }

    @Override
    public List<Homework> getStudentHomeworks(Integer studentId) {
        return homeworkMapper.findByStudentId(studentId);
    }

    @Override
    public void updateHomeworkStatus(Integer id, Integer status) {
        homeworkMapper.updateStatus(id, status);
    }

    @Override
    public void addQuestion(HomeworkQuestion question) {
        questionMapper.insert(question);
    }

    @Override
    public void updateQuestion(HomeworkQuestion question) {
        questionMapper.update(question);
    }

    @Override
    public void deleteQuestion(Integer questionId) {
        questionMapper.delete(questionId);
    }

    @Override
    public List<HomeworkQuestion> getQuestionsByHomeworkId(Integer homeworkId) {
        return questionMapper.findByHomeworkId(homeworkId);
    }

    @Override
    public void submitAnswer(HomeworkAnswer answer) {
        answerMapper.insert(answer);
    }

    @Override
    public void updateAnswer(Integer answerId, String answerContent) {
        answerMapper.updateStudentAnswer(answerId, answerContent);
    }

    @Override
    public List<HomeworkAnswer> getAnswersByHomeworkAndStudent(Integer homeworkId, Integer studentId) {
        return answerMapper.findByHomeworkAndStudentId(homeworkId, studentId);
    }

    @Override
    @Transactional
    public void gradeAnswer(Integer answerId, String teacherComment, Integer score) {
        // 获取答案信息
        HomeworkAnswer answer = answerMapper.findById(answerId);
        if (answer == null) {
            throw new RuntimeException("答案不存在");
        }

        // 获取题目信息
        HomeworkQuestion question = questionMapper.findById(answer.getQuestionId());
        if (question == null) {
            throw new RuntimeException("题目不存在");
        }

        // 更新答案的评分和评语
        answerMapper.updateTeacherFeedback(answerId, teacherComment, score);

        // 如果得分不是满分，添加到错题本
        if (score < question.getScore()) {
            // 检查是否已经存在于错题本中
            MistakeBook existingMistake = mistakeBookService.findByStudentAndQuestion(
                answer.getStudentId(), 
                question.getId()
            );

            if (existingMistake != null) {
                // 更新已存在的错题记录
                existingMistake.setStudentAnswer(answer.getAnswerContent());
                existingMistake.setScore(score);
                existingMistake.setTeacherComment(teacherComment);
                mistakeBookService.updateMistake(existingMistake);
            } else {
                // 创建新的错题记录
                MistakeBook mistakeBook = new MistakeBook();
                mistakeBook.setStudentId(answer.getStudentId());
                mistakeBook.setHomeworkId(answer.getHomeworkId());
                mistakeBook.setQuestionId(question.getId());
                mistakeBook.setAnswerId(answerId);
                mistakeBook.setStudentAnswer(answer.getAnswerContent());
                mistakeBook.setStandardAnswer(question.getStandardAnswer());
                mistakeBook.setScore(score);
                mistakeBook.setMaxScore(question.getScore());
                mistakeBook.setTeacherComment(teacherComment);
                
                mistakeBookService.addMistake(mistakeBook);
            }
        }
    }

    @Override
    @Transactional
    public void autoGradeAnswer(Integer answerId) {
        // 获取答案信息
        HomeworkAnswer answer = answerMapper.findById(answerId);
        if (answer == null) {
            throw new RuntimeException("答案不存在");
        }

        // 获取题目信息
        HomeworkQuestion question = questionMapper.findById(answer.getQuestionId());
        if (question == null) {
            throw new RuntimeException("题目不存在");
        }

        String teacherComment;
        int score;

        // 根据题目类型进行自动批改
        switch (question.getQuestionType()) {
            case 1: // 选择题
                boolean isCorrect = answer.getAnswerContent().trim().equalsIgnoreCase(question.getStandardAnswer().trim());
                score = isCorrect ? question.getScore() : 0;
                teacherComment = isCorrect ? "答案正确" : "答案错误，正确答案是：" + question.getStandardAnswer();
                break;

            case 2: // 填空题
                double similarity = calculateAnswerSimilarity(answer.getAnswerContent(), question.getStandardAnswer());
                if (similarity >= 0.9) { // 90%以上相似度认为完全正确
                    score = question.getScore();
                    teacherComment = "答案正确";
                } else if (similarity >= 0.7) { // 70%-90%相似度给部分分
                    score = (int) (question.getScore() * similarity);
                    teacherComment = "答案部分正确，完整答案是：" + question.getStandardAnswer();
                } else {
                    score = 0;
                    teacherComment = "答案错误，正确答案是：" + question.getStandardAnswer();
                }
                break;

            case 3: // 简答题
            case 4: // 综合题
                similarity = calculateAnswerSimilarity(answer.getAnswerContent(), question.getStandardAnswer());
                // 主观题的评分更宽松
                score = (int) (question.getScore() * similarity);
                if (similarity >= 0.8) {
                    teacherComment = "答案完整，表述准确";
                } else if (similarity >= 0.6) {
                    teacherComment = "答案基本正确，但有待完善。参考答案：" + question.getStandardAnswer();
                } else {
                    teacherComment = "答案有待改进。参考答案：" + question.getStandardAnswer();
                }
                break;

            default:
                throw new RuntimeException("未知的题目类型");
        }

        // 更新答案的评分和评语
        answerMapper.updateTeacherFeedback(answerId, teacherComment, score);

        // 如果得分不是满分，添加到错题本
        if (score < question.getScore()) {
            MistakeBook existingMistake = mistakeBookService.findByStudentAndQuestion(
                answer.getStudentId(), 
                question.getId()
            );

            if (existingMistake != null) {
                existingMistake.setStudentAnswer(answer.getAnswerContent());
                existingMistake.setScore(score);
                existingMistake.setTeacherComment(teacherComment);
                mistakeBookService.updateMistake(existingMistake);
            } else {
                MistakeBook mistakeBook = new MistakeBook();
                mistakeBook.setStudentId(answer.getStudentId());
                mistakeBook.setHomeworkId(answer.getHomeworkId());
                mistakeBook.setQuestionId(question.getId());
                mistakeBook.setAnswerId(answerId);
                mistakeBook.setStudentAnswer(answer.getAnswerContent());
                mistakeBook.setScore(score);
                mistakeBook.setMaxScore(question.getScore());
                mistakeBook.setTeacherComment(teacherComment);
                
                mistakeBookService.addMistake(mistakeBook);
            }
        }
    }

    @Override
    @Transactional
    public void autoGradeHomework(Integer homeworkId, Integer studentId) {
        List<HomeworkAnswer> answers = answerMapper.findByHomeworkAndStudentId(homeworkId, studentId);
        for (HomeworkAnswer answer : answers) {
            autoGradeAnswer(answer.getId());
        }
        // 更新作业状态为已批改
        updateHomeworkStatus(homeworkId, 2);
    }

    @Override
    public double calculateAnswerSimilarity(String studentAnswer, String standardAnswer) {
        if (studentAnswer == null || standardAnswer == null) {
            return 0.0;
        }

        // 将答案转换为小写并去除多余空格
        String s1 = studentAnswer.toLowerCase().trim();
        String s2 = standardAnswer.toLowerCase().trim();

        if (s1.equals(s2)) {
            return 1.0;
        }

        // 使用编辑距离算法计算相似度
        int[][] dp = new int[s1.length() + 1][s2.length() + 1];

        for (int i = 0; i <= s1.length(); i++) {
            dp[i][0] = i;
        }
        for (int j = 0; j <= s2.length(); j++) {
            dp[0][j] = j;
        }

        for (int i = 1; i <= s1.length(); i++) {
            for (int j = 1; j <= s2.length(); j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(dp[i - 1][j - 1] + 1,
                                      Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1));
                }
            }
        }

        int maxLength = Math.max(s1.length(), s2.length());
        if (maxLength == 0) {
            return 1.0;
        }

        return 1.0 - (double) dp[s1.length()][s2.length()] / maxLength;
    }

    @Override
    public List<HomeworkQuestion> generateQuestionsByAI(Integer categoryId, Integer knowledgePointId, 
                                                      Integer questionType, Integer questionCount,
                                                      String topic) {
        List<HomeworkQuestion> questions = new ArrayList<>();
        
        // 如果没有提供主题，则使用知识点信息作为主题
        if (topic == null || topic.trim().isEmpty()) {
            topic = getKnowledgePointTopic(knowledgePointId);
        }
        
        for (int i = 0; i < questionCount; i++) {
            HomeworkQuestion question = new HomeworkQuestion();
            question.setQuestionType(questionType);
            question.setKnowledgePointId(knowledgePointId);
            
            // 生成题目内容
            String questionContent = aiService.generateQuestionContent(topic, questionType);
            question.setQuestionContent(questionContent);
            
            // 生成标准答案
            String standardAnswer = aiService.generateStandardAnswer(questionContent, questionType);
            question.setStandardAnswer(standardAnswer);
            
            // 如果是选择题，生成选项
            if (questionType == 1) {
                List<String> options = aiService.generateOptions(questionContent, standardAnswer);
                question.setQuestionOptions(convertOptionsToJson(options));
            }
            
            // 设置默认分值
            question.setScore(10);
            
            questions.add(question);
        }
        
        return questions;
    }

    @Override
    public String generateQuestionContent(String topic, Integer questionType) {
        return aiService.generateQuestionContent(topic, questionType);
    }

    @Override
    public String generateStandardAnswer(String questionContent, Integer questionType) {
        return aiService.generateStandardAnswer(questionContent, questionType);
    }

    @Override
    public List<String> generateOptions(String questionContent, String standardAnswer) {
        return aiService.generateOptions(questionContent, standardAnswer);
    }

    private String getKnowledgePointTopic(Integer knowledgePointId) {
        // 这里需要实现获取知识点信息的逻辑
        // 可以通过注入KnowledgePointService来实现
        return "示例主题";
    }

    private String convertOptionsToJson(List<String> options) {
        List<Map<String, String>> optionsList = new ArrayList<>();
        for (String option : options) {
            Map<String, String> optionMap = new HashMap<>();
            optionMap.put("content", option);
            optionsList.add(optionMap);
        }
        try {
            return new ObjectMapper().writeValueAsString(optionsList);
        } catch (Exception e) {
            throw new RuntimeException("转换选项为JSON失败", e);
        }
    }
} 